from Tile import Tile
from Coodinate import Coordinate
from terrainEntities import *
from Monsters import *

def genereate(map):
    import datetime

    width = map.width
    height = map.height

    start = datetime.datetime.today()

    # The tiles on the map
    map.tiles = [[Tile(Coordinate(x, y))
        for y in range(height)]
            for x in range(width)]


    generateBasicTerrain(map)

    centerHeight = map.height / 2
    startPos = 0
    for x in range(width):
        if map.tiles[x][centerHeight].stack[0].name == "Rock Wall":
            startPos = x
            break

    # Draw the Tunnel into the Dark Lords Cell
    upperLeft = Coordinate(0, centerHeight - 1)
    size = Coordinate(startPos + 20, 3)
    drawRectangle(map, rockFloor, "Rock Wall", upperLeft, size)

    # Draw the Dark Lords Cell
    upperLeft = Coordinate(startPos + 20, centerHeight - 3)
    size = Coordinate(7, 7)
    drawRectangle(map, rockFloor, "Rock Wall", upperLeft, size)

    # Create the dark lord
    pos = Coordinate(startPos+23, centerHeight)
    dl = DarkLord(1)
    map.addEntity(dl, pos)

    end = datetime.datetime.today()

    print str(end - start)

    return


def generateBasicTerrain(map):
    from random import randint

    width = map.width
    height = map.height

    stickOutynes = width - int(width*3/float(4))
    stickOutynesOrigin = stickOutynes

    for y in range(height):

        stickOutynes += randint(-2, 2)
        if stickOutynes + 25 > stickOutynesOrigin:
            stickOutynes -= 1
        if stickOutynes - 25 < stickOutynesOrigin:
            stickOutynes += 1


        for x in range(width):

            pos = Coordinate(x, y)

            if x > stickOutynes:
                wall = rockWall()

                map.addEntity(wall, pos)
            else:
                grassFloor = grass()
                map.addEntity(grassFloor, pos)

##
# drawRectangle
#
#
def drawRectangle(map, creationFunction, replaceName, upperLeft, size):

    for localX in range(size.x):
        for localY in range(size.y):

            absX = upperLeft.x + localX
            absY = upperLeft.y + localY

            obj = map.tiles[absX][absY].stack[0]
            if obj.name == replaceName:
                map.removeEntity(obj)
                del obj

                obj = creationFunction()
                map.addEntity(obj, Coordinate(absX, absY))
